import org.devops.*

def getTriggerSource() {
    triggerFrom = "jenkins"
    try {
        // 如果是gitlab过来的http请求,会带有triggerType参数,如下所示:
        // https://jenkins.devops.com/generic-webhook-trigger/invoke?token=${JOB_NAME}&triggerType=GitlabPush
        if ("${env.triggerType}" == "GitlabPush") {
            triggerFrom = "gitlab"
        }
    } catch (Exception e) {}
    return triggerFrom;
}

def initialize() {
    this.tools  = new Tools()
    this.build  = new Build()
    this.gitlab = new Gitlab()
    this.sonar  = new Sonar()
    this.docker = new Docker()
    this.ding   = new Ding()
}

def setEnvVars() {
    // k8s中的namespace,支持两种: dev test
    if (env.triggerFrom == "jenkins") {
        wrap([$class: 'BuildUser']) {
            env.triggerUser = env.BUILD_USER_ID
        }
        if (env.branchName.startsWith("origin/")) {
            env.branch = env.branchName - "origin/"
            env.namespace = "dev"
        } else {
            env.branch = env.branchName
            env.namespace = "test"
        }
    } else {
        env.triggerUser = env.userName
        env.branch = env.branchName - "refs/heads/"
        env.namespace = "dev"
    }
    currentBuild.description = "Triggered by ${env.triggerUser}, branch ${env.branch}"

    // 打印jenkins任务控制台的配置参数(如果是由gitlab触发,则branchName参数会被替换为gitlab传递过来的值)
    printColor("triggerFrom: ${env.triggerFrom} \n "
            + "triggerUser: ${env.triggerUser} \n "
            + "gitlabAddr: ${env.gitlabAddr} \n "
            + "branch: ${env.branch} \n "
            + "namespace: ${env.namespace} \n "
            + "buildType: ${env.buildType} \n "
            + "buildCmd: ${env.buildCmd} \n "
            + "port: ${env.port}",
            "green")
}

def gitlabCheckout(gitlabAddr, branch, gitlabUid) {
    shortCommitId = gitlab.checkout(gitlabAddr, branch, gitlabUid)

    if (env.namespace == "dev") {
        env.tagName = branch + "_" + shortCommitId
    } else {
        env.tagName = branch
    }

    printColor("tagName: ${env.tagName}", "green")
}

def setGitlabCommitStatus(status) {
    return gitlab.setCommitStatus(status)
}

def mavenBuild(buildType, buildCmd) {
    return build.build(buildType, buildCmd)
}

def sonarScan(projectName, projectDesc, tagName, branch) {
    def qualityProfile = "demo"
    def gateName = "demo"

    printColor("搜索sonar项目: ${projectName}", "green")
    exist = sonar.searchProject(projectName)
    if (exist == "false") {
        printColor("sonar项目不存在，创建项目 --> ${projectName}", "green")
        sonar.createProject(projectName)

        printColor("配置项目${projectName}的质量规则${qualityProfile}", "green")
        sonar.configQualityProfiles(projectName, "java", qualityProfile)

        printColor("配置项目${projectName}的质量阈${gateName}", "green")
        sonar.configQualityGates(projectName, gateName)
    } else {
        printColor("sonar项目${projectName}已存在", "green")
    }

    printColor("代码扫描......", "green")
    sonar.sonarScan(projectName, projectDesc, tagName, branch)

    printColor("获取扫描结果", "green")
    result = sonar.getProjectStatus(projectName)
    println(result)

    if (result.toString() == "ERROR") {
        error " 代码质量阈错误！请及时修复！"
    }
}

def dockerBuild(harborAddr, groupName, appName, tagName, harborUid) {
    imageName = "${harborAddr}/${groupName}/${appName}:${tagName}"

    docker.init(harborAddr, harborUid, appName, imageName, "devops/Dockerfile.template")
            .login().build().push()
}

def deploy(harborAddr, groupName, appName, tagName, namespace, port, domainName) {
    imageName = "${harborAddr}/${groupName}/${appName}:${tagName}"

    ymlName = "devops/${appName}.yml"
    sh """
          /bin/cp  devops/deploy.template              ${ymlName}
          sed -i  's#{{imageName}}#${imageName}#g'     ${ymlName}
          sed -i  's#{{appName}}#${appName}#g'         ${ymlName}
          sed -i  's#{{namespace}}#${namespace}#g'     ${ymlName}
          sed -i  's#{{port}}#${port}#g'               ${ymlName}
          sed -i  's#{{domainName}}#${domainName}#g'   ${ymlName}
       """
    withKubeConfig([credentialsId: 'kubernetes-kubeconfig', serverUrl: 'https://kubernetes.default']) {
        sh "/usr/local/bin/kubectl apply -f ${ymlName}"
    }
}

def sendDingTalk(dingUid, appName, tagName, status, catchInfo = ' ') {
    ding.send(dingUid, appName, tagName, status, catchInfo)
}

def printColor(message, color) {
    tools.printColor(message, color)
}
